package com.chtw.oasystem.service.impl;

import com.chtw.oasystem.bean.*;
import com.chtw.oasystem.common.changelogs.ChangeLogsUtils;
import com.chtw.oasystem.mapper.TrainMapper;
import com.chtw.oasystem.mapper.TrainUserMapper;
import com.chtw.oasystem.mapper.UsersMapper;
import com.chtw.oasystem.respBean.TrainResp;
import com.chtw.oasystem.respBean.UserResp;
import com.chtw.oasystem.service.TrainService;
import com.chtw.oasystem.utils.Session;
import com.chtw.oasystem.utils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenhao03
 * @create 2020-11-21 14:19
 */
@Service
public class TrainServiceImpl implements TrainService {
    @Autowired
    private TrainMapper trainMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private TrainUserMapper trainUserMapper;

    @Autowired
    private ChangeLogServiceImpl changeLogService;

    private List<Users> getUsersByIds(List<TrainUser> trainUsers) {
        List<Users> users = new ArrayList<>();
        for (TrainUser trainUser : trainUsers) {
            UsersExample example = new UsersExample();
            UsersExample.Criteria re = example.createCriteria();
            re.andUserIdEqualTo(trainUser.getUserId());
            users.addAll(usersMapper.selectByExample(example));
        }
        return users;
    }

    @Override
    public PageInfo<TrainResp> list(String search, int page, int size) {
        try {
            PageHelper.startPage(page, size);
            TrainExample example = new TrainExample();
            if (search != null) {
                example.or().andTopicLike("%" + search + "%");
                example.or().andDescriptionLike("%" + search + "%");
            }
            List<Train> trainList = trainMapper.selectByExample(example);
            PageInfo<Train> trainPageInfo = new PageInfo<>(trainList);
            List<TrainResp> trainResps = new ArrayList<>();
            for (Train train : trainList) {
                TrainUserExample trainUserExample = new TrainUserExample();
                TrainUserExample.Criteria re = trainUserExample.createCriteria();
                re.andTrainIdEqualTo(String.valueOf(train.getId()));
                List<TrainUser> trainUsers = trainUserMapper.selectByExample(trainUserExample);
                List<Users> users = this.getUsersByIds(trainUsers);
                List<UserResp> resUsers = new ArrayList<>();
                List<String> userIds = new ArrayList<>();
                users.forEach(user -> {
                    userIds.add(user.getUserId());
                    resUsers.add(new UserResp(user.getUserId(), user.getUserName(), user.getWorkId()));
                });
                TrainResp resp = new TrainResp(train.getId(), train.getTrainName(),
                        train.getTopic(), train.getSpeaker(), train.getShowTime(), train.getDescription(), resUsers, userIds
                );
                trainResps.add(resp);
            }
            PageInfo<TrainResp> info = new PageInfo<>(trainResps);
            info.setTotal(trainPageInfo.getTotal());
            info.setPages(trainPageInfo.getPages());
            info.setList(trainResps);
            return info;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public TrainResp info(int id) {
        try {
            Train train = trainMapper.selectByPrimaryKey(id);
            TrainUserExample trainUserExample = new TrainUserExample();
            TrainUserExample.Criteria re = trainUserExample.createCriteria();
            re.andTrainIdEqualTo(String.valueOf(train.getId()));
            List<TrainUser> trainUsers = trainUserMapper.selectByExample(trainUserExample);
            List<Users> users = this.getUsersByIds(trainUsers);
            List<UserResp> resUsers = new ArrayList<>();
            List<String> userIds = new ArrayList<>();
            users.forEach(user -> {
                userIds.add(user.getUserId());
                resUsers.add(new UserResp(user.getUserId(), user.getUserName(), user.getWorkId()));
            });
            return new TrainResp(train.getId(),train.getTrainName(),
                    train.getTopic(), train.getSpeaker(), train.getShowTime(), train.getDescription(), resUsers, userIds
            );
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public boolean create(HttpSession session, TrainResp train) {
        try {
            FullUserInfo currentUser = Session.getCurrentUser(session);
            if (currentUser == null) {
                throw new RuntimeException("用户未登录！");
            } else if (currentUser.getRoleId() < 1) {
                Train newTrain = new Train();
                newTrain.setCreated(TimeUtils.currentTimeMillis());
                newTrain.setDescription(train.getDescription());
                newTrain.setShowTime(train.getShowTime());
                newTrain.setSpeaker(train.getSpeaker());
                newTrain.setTrainName(train.getTrainName());
                newTrain.setTopic(train.getTopic());
                int isCreated = trainMapper.insert(newTrain);
                if (train.getUserIds() != null && train.getUserIds().size() > 0) {
                    List<String> userIds = train.getUserIds();
                    for (String userId : userIds) {
                        TrainUser t = new TrainUser();
                        t.setTrainId(String.valueOf(newTrain.getId()));
                        t.setUserId(userId);
                        trainUserMapper.insert(t);
                    }
                }
                changeLogService.saveChangeLog(ChangeLogsUtils.generateTrainChangeLog(currentUser.getUserName(), train.getTrainName(), "增加"));
                return isCreated > 0;
            } else {
                throw new RuntimeException("没有权限");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    @Override
    public boolean edit(HttpSession session, TrainResp train) {
        try {
            FullUserInfo currentUser = Session.getCurrentUser(session);
            if (currentUser == null) {
                throw new RuntimeException("用户未登录！");
            } else if (currentUser.getRoleId() < 1) {
                Train newTrain = new Train();
                newTrain.setCreated(TimeUtils.currentTimeMillis());
                newTrain.setDescription(train.getDescription());
                newTrain.setShowTime(train.getShowTime());
                newTrain.setSpeaker(train.getSpeaker());
                newTrain.setTrainName(train.getTrainName());
                newTrain.setTopic(train.getTopic());
                int isEdit = trainMapper.updateByPrimaryKeySelective(newTrain);
                changeLogService.saveChangeLog(ChangeLogsUtils.generateTrainChangeLog(currentUser.getUserName(), train.getTrainName(), "编辑"));
                return isEdit > 0;
            } else {
                throw new RuntimeException("没有权限");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public boolean delete(HttpSession session, int id) {
        try {
            FullUserInfo currentUser = Session.getCurrentUser(session);
            if (currentUser == null) {
                throw new RuntimeException("用户未登录！");
            } else if (currentUser.getRoleId() < 1) {
                Train train = trainMapper.selectByPrimaryKey(id);
                int idDel = trainMapper.deleteByPrimaryKey(id);
                changeLogService.saveChangeLog(ChangeLogsUtils.generateTrainChangeLog(currentUser.getUserName(), train.getTrainName(), "删除"));
                return idDel > 0;
            } else {
                throw new RuntimeException("没有权限");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
